package com.xiaobai.thread;

import org.apache.log4j.Logger;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 业务自定义线程工程
 * @author wangt
 */
public class BusinessThreadFactory implements ThreadFactory {

    private final Logger logger = Logger.getLogger(BusinessThreadFactory.class);

    // 线程组
    private final ThreadGroup group;

    // 线程序号
    private final AtomicInteger threadNumber = new AtomicInteger(1);

    // 线程名称前缀
    private final String namePrefix;

    public BusinessThreadFactory(String namePrefix) {
        SecurityManager securityManager = System.getSecurityManager();
        group = securityManager != null ? securityManager.getThreadGroup()
                : Thread.currentThread().getThreadGroup();

        this.namePrefix = namePrefix + "-thread-";
    }

    @Override
    public Thread newThread(Runnable runnable) {

        Thread thread = new Thread(group, runnable, namePrefix + threadNumber.getAndIncrement(), 0);

        // 守护线程
        if (thread.isDaemon()) {
            // 将当前线程设置为守护线程，主线程结束时，当前线程也随之结束
            thread.setDaemon(true);
        }

        // 线程优先级
        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            // 设置普通优先级
            thread.setPriority(Thread.NORM_PRIORITY);
        }

        // 处理未捕捉的异常
        thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                logger.error("异常：", e);
            }
        });

        return thread;
    }
}
